<template>
  <el-upload
    class="tn-upload-file"
    :action="uploadFileUrl"
    :multiple="true"
    :headers="uploadHeaders"
    :data="uploadData"
    :file-list="fileList"
    :on-success="fileUploadSuccess"
    :on-error="fileUploadError"
    :before-remove="fileBeforeRemove"
  >
    <el-button size="small" type="primary">点击上传</el-button>
  </el-upload>
</template>

<script>
import { getToken } from '../../../utils/auth'
import store from '../../../store'
import { deleteUploadTempFile } from '../../../api/upload'

export default {
  name: 'UploadFile',
  model: {
    prop: 'value',
    event: 'changeModelVal'
  },
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      }
    },
    saveDirName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileList: this.value,
      tempUploadList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_URL + process.env.VUE_APP_IMAGE_UPLOAD_API,
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadData: {
        type: 'file',
        dir_name: this.saveDirName
      }
    }
  },
  watch: {
    // value(val) {
    //   this.fileList = val
    // }
  },
  created() {
    this.value.forEach((item, index) => {
      this.tempUploadList[index] = {
        name: item.name,
        status: 'success',
        url: item.url
      }
    })
    this.changeValue(this.tempUploadList)
  },
  methods: {
    changeValue(val) {
      this.$emit('changeModelVal', val)
      this.$emit('change', val)
    },
    fileUploadSuccess(response, file, fileList) {
      const { data } = response
      // console.log(data, fileList, this.fileList)

      this.tempUploadList.push({
        name: data.origin_name,
        url: data.save_path,
        status: 'success'
      })
      // console.log(this.tempUploadList)
      this.changeValue(this.tempUploadList)
    },
    fileUploadError(err, file, fileList) {
      if (err) {
        // console.log(err, file, fileList)
        // console.log(err.message)
        const message = err.message ? JSON.parse(err.message) : { msg: '上传图片失败', errorCode: 0 }
        this.$message({
          message: message.msg,
          type: 'error'
        })
        // err = JSON.stringify(err.message)
        if (message.errorCode === 30000 || message.errorCode === 30001) {
          // console.log('upload reset')
          // to re-login
          this.$confirm('Token 已失效，请重新登陆', '确认登出', {
            confirmButtonText: '重新登陆',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          }).catch(() => {})
        }
      }
    },
    fileBeforeRemove(file, fileList) {
      // console.log(file, fileList)
      const file_name = file.url || file.response.data.save_path
      return deleteUploadTempFile({
        file_name
      }).then(response => {
        if (response.errorCode === 0) {
          this.tempUploadList.forEach((item, index) => {
            if (item.url === file_name) {
              this.tempUploadList.splice(index, 1)
              this.changeValue(this.tempUploadList)
              return false
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
